package com.tutk.P2PCam264;


import android.app.Notification;
import android.app.Notification.BigPictureStyle;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.NotificationCompat;
import android.util.Log;

import com.tutk.agza.BaseAgzaReceiver;
import com.tutk.agza.NotifyInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import cn.innosmart.aq.R;


/**
 * Created by huanlinchen on 2/12/2015.
 */
public class AgzaReceiver extends BaseAgzaReceiver {
    public static final String AGZA_USERNAME = "agza_p2pcamlive";
    public static final String AGZA_PASSWORD = "MTY1YTZjYWZjOTRjYzhmZGNmMjgzNzQzZjM3ZmI1NTA=";
    private static int mNotifyCount = 0;
    private static final String TAG = "AgzaReceiver";
    private String imageFileURL = "https://dl.dropboxusercontent.com/u/24682760/Android_AS/DownloadImageDemo/monkey.png";

    @Override
    public void onReceiveNotify(NotifyInfo notifyInfo) {

//        Bitmap largeIcon = BitmapFactory.decodeResource(getContext().getResources(),R.drawable.splash_320x480);

        if (notifyInfo.getMIME() != null) {
            if (notifyInfo.getMIME().substring(0, 5).equals("image")) {
                new DownloadWebPicture().getURLimg(notifyInfo.getFile(), notifyInfo, getContext());
                Log.d("TPNS", "URL");
            } else {
                //Notification Push Video
                Bundle extars = new Bundle();
                extars.putString("dev_uid", notifyInfo.getUID());
                extars.putString("file", notifyInfo.getFile());
                extars.putString("mime", notifyInfo.getMIME());
                extars.putString("Agza","AgzaMedia");

                Intent intent = new Intent(getContext(), MainActivity.class);
                intent.putExtras(extars);

                if (!notifyInfo.getEventType().equalsIgnoreCase("2000"))
                    extars.putString("event_type", "");
                else {
                    extars.putString("event_type", notifyInfo.getEventType());
                }

                NotificationManager manager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);

                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                //FLAG_UPDATE_CURRENT 表示 PendingIntent 更新資料 通知訊息的點擊事件
                PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                Calendar cal = Calendar.getInstance();     //取得當前時間
                cal.setTimeZone(TimeZone.getDefault()); //取的當前時間
                cal.setTimeInMillis(notifyInfo.getEventTime() * 1000);
                cal.add(Calendar.MONTH, 0); //設定月+0

                Notification notification = new Notification(R.drawable.nty_alert, notifyInfo.getAlert(), cal.getTimeInMillis());
                NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext());

                notification.flags |= Notification.FLAG_AUTO_CANCEL;
                notification.flags |= Notification.FLAG_NO_CLEAR;
                notification.defaults = Notification.DEFAULT_ALL;
                notification.defaults = Notification.DEFAULT_VIBRATE;

                DatabaseManager dbman = new DatabaseManager(getContext());
                SQLiteDatabase db = dbman.getReadableDatabase();
                Cursor cursor = db.query(DatabaseManager.TABLE_DEVICE, new String[]{"_id", "dev_nickname", "dev_uid", "dev_name", "dev_pwd",
                                "view_acc", "view_pwd", "event_notification", "camera_channel", "snapshot", "ask_format_sdcard"}, null, null, null, null,
                        "_id LIMIT " + MainActivity.CAMERA_MAX_LIMITS);

                while (cursor.moveToNext()) {
                    String dev_nickname = cursor.getString(1);
                    String dev_uid = cursor.getString(2);

                    if (dev_uid.equals(notifyInfo.getUID())) {
                        notification.setLatestEventInfo(getContext(), String.format(getContext().getText(R.string.ntfIncomingEvent).toString(), dev_nickname
                        ), String.format(getContext().getText(R.string.ntfLastEventIs).toString(), notifyInfo.getAlert()), pendingIntent);
                    } else {
                        Log.d("TPNS", "not UID");
                    }

                }

                manager.notify(1, notification);
                Log.d("TPNS", "push eddie video");

                file(cal, notifyInfo, "Video");
                Log.d("TPNS", "file video");

            }

        } else {
            //Notification  Push String
            Bundle extars = new Bundle();
            extars.putString("dev_uid", notifyInfo.getUID());
            extars.putString("Agza","AgzaStringPush");

            Intent intent = new Intent(getContext(), MainActivity.class);
            intent.putExtras(extars);

            if (!notifyInfo.getEventType().equalsIgnoreCase("2000"))
                extars.putString("event_type", "");
            else {
                extars.putString("event_type", notifyInfo.getEventType());
                Log.d("TPNS","event_type " + notifyInfo.getEventType());
            }

            NotificationManager manager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);

            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            //FLAG_UPDATE_CURRENT 表示 PendingIntent 更新資料 通知訊息的點擊事件
            PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            Calendar cal = Calendar.getInstance();     //取得當前時間
            cal.setTimeZone(TimeZone.getDefault()); //取的當前時間
            cal.setTimeInMillis(notifyInfo.getEventTime() * 1000);
            cal.add(Calendar.MONTH, 0); //設定月+0

            Notification notification = new Notification(R.drawable.nty_alert, notifyInfo.getAlert(), cal.getTimeInMillis());

            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notification.flags |= Notification.FLAG_NO_CLEAR;
            notification.defaults = Notification.DEFAULT_ALL;
            notification.defaults = Notification.DEFAULT_VIBRATE;

            DatabaseManager dbman = new DatabaseManager(getContext());
            SQLiteDatabase db = dbman.getReadableDatabase();
            Cursor cursor = db.query(DatabaseManager.TABLE_DEVICE, new String[]{"_id", "dev_nickname", "dev_uid", "dev_name", "dev_pwd",
                            "view_acc", "view_pwd", "event_notification", "camera_channel", "snapshot", "ask_format_sdcard"}, null, null, null, null,
                    "_id LIMIT " + MainActivity.CAMERA_MAX_LIMITS);

            while (cursor.moveToNext()) {
                String dev_nickname = cursor.getString(1);
                String dev_uid = cursor.getString(2);

                if (dev_uid.equals(notifyInfo.getUID())) {
                    notification.setLatestEventInfo(getContext(), String.format(getContext().getText(R.string.ntfIncomingEvent).toString(), dev_nickname
                    ), String.format(getContext().getText(R.string.ntfLastEventIs).toString(), notifyInfo.getAlert()), pendingIntent);
                } else {
                    Log.d("TPNS", "not UID");
                }

            }

            manager.notify(1, notification);
            Log.d("TPNS", "push eddie String" );

            file(cal,notifyInfo,"String");
            Log.d("TPNS", "file String");
        }

    }
    //Notification Push Image
    public static void getBitmapReceiveNotify(Bitmap bitmap, NotifyInfo notifyInfo, Context ctx) throws ParseException {

        Bundle extars = new Bundle();
        extars.putString("dev_uid", notifyInfo.getUID());
        extars.putString("file", notifyInfo.getFile());
        extars.putString("mime", notifyInfo.getMIME());
        extars.putString("Agza","AgzaMedia");

        if (!notifyInfo.getEventType().equalsIgnoreCase("2000"))
            extars.putString("event_type", "");
        else {
            extars.putString("event_type", notifyInfo.getEventType());
        }

        Intent intent = new Intent(ctx, MainActivity.class);
        intent.putExtras(extars);


        NotificationManager manager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        //FLAG_UPDATE_CURRENT 表示 PendingIntent 更新資料 通知訊息的點擊事件
        PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Calendar cal = Calendar.getInstance();     //取得當前時間
        cal.setTimeZone(TimeZone.getDefault()); //取的當前時間
        cal.setTimeInMillis(notifyInfo.getEventTime() * 1000);
        cal.add(Calendar.MONTH, 0); //設定月+0
        
        Builder builder = new Builder(ctx);
        BigPictureStyle bigPictureStyle = new BigPictureStyle().bigPicture(bitmap);

//        NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);

        DatabaseManager dbman = new DatabaseManager(ctx);
        SQLiteDatabase db = dbman.getReadableDatabase();
        Cursor cursor = db.query(DatabaseManager.TABLE_DEVICE, new String[]{"_id", "dev_nickname", "dev_uid", "dev_name", "dev_pwd",
                        "view_acc", "view_pwd", "event_notification", "camera_channel", "snapshot", "ask_format_sdcard"}, null, null, null, null,
                "_id LIMIT " + MainActivity.CAMERA_MAX_LIMITS);

//        NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
//        bigPictureStyle.bigPicture(bitmap);

        //getTimeInMillis 取的當前時間
        while (cursor.moveToNext()) {
            String dev_nickname = cursor.getString(1);
            String dev_uid = cursor.getString(2);

            if (dev_uid.equals(notifyInfo.getUID())) {

                builder.setSmallIcon(R.drawable.nty_alert).setWhen(System.currentTimeMillis())
                        .setContentIntent(pendingIntent)
                        .setContentText(String.format(ctx.getText(R.string.ntfLastEventIs).toString(), notifyInfo.getAlert()))
                        .setContentTitle(String.format(ctx.getText(R.string.ntfIncomingEvent).toString(), dev_nickname))
                        .setStyle(bigPictureStyle);
            } else {
                Log.d("TPNS", "not UID");
            }
        }

        Log.d("Agza", "TPNS" + "file " + notifyInfo.getFile() + "MIME " + notifyInfo.getMIME());

        Notification notification = builder.build();
        //FLAG_AUTO_CANCEL 點擊了通知事件之後自動清除此通知
        //FLAG_NO_CLEAR 表示點擊通知欄的清除通知後此通知不清除
        //DEFAULT_VIBRATE 設置震動
        //DEFAULT_ALL 所有屬性設置成默認
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.flags |= Notification.FLAG_NO_CLEAR;
        notification.defaults = Notification.DEFAULT_ALL;
        notification.defaults = Notification.DEFAULT_VIBRATE;

        manager.notify(1, notification);
        Log.d("TPNS", "push eddie image");

        file(cal, notifyInfo, "Image");
        Log.d("TPNS", "file Image ");

    }

    @Override
    protected String getPassword() {
        return AGZA_PASSWORD;
    }

    @Override
    protected String getUsername() {
        return AGZA_USERNAME;
    }



    public static void file(Calendar calendar, NotifyInfo notifyInfo, String types){
        long dv = calendar.getTimeInMillis();
        Date cv = new Date(dv);
        String datetime = new SimpleDateFormat("MM dd, yyyy hh:mm:ss").format(cv);
        long dc = System.currentTimeMillis();
        Date ac = new Date(dc);
        String nowtime = new SimpleDateFormat("MM dd, yyyy hh:mm:ss").format(ac);

        SimpleDateFormat sdf = new SimpleDateFormat("MM dd, yyyy hh:mm:ss");
        Date now = null;
        Date date = null;
        try {
            now = sdf.parse(nowtime);
            date = sdf.parse(datetime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long l = now.getTime() - date.getTime();

        long day = l / (24 * 60 * 60 * 1000);
        long hour = (l / (60 * 60 * 1000) - day * 24);
        long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);

        Log.d("TPNS", "TIME " + notifyInfo.getEventTime() + "TIMEC " + System.currentTimeMillis() + "datetime " + datetime + "nowtime " + nowtime + " = " + s);

        String message = "datetime: " + datetime + " nowtime: " + nowtime + " = " + s + "sec - " + types;

        try {
            File rootFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/P2PCamLive_Agza/");
            if (!rootFolder.exists()) {
                rootFolder.mkdir();
            }

            FileOutputStream output = new FileOutputStream(rootFolder.getAbsolutePath() + "/Agza.txt", true);
            output.write(message.getBytes());
            output.write("\n".getBytes());
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}